import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import {loginApi,getUserDetailApi} from '../api/loginRequest.js'
import { ElMessage } from 'element-plus'
export const useStateStore = defineStore( 'state',()=>
{
    const token = ref('')
    const isLogin = ref(false)
    const userDetail = ref({})
    const login =  (data)=>{
        const response =  loginApi(data).then(res=>{
            if(res.data.status === "success")
            {
                token.value = res.data.token
                isLogin.value = true
                ElMessage({
                    message: 'Login Success',
                    type: 'success',
                })
                return true
            }
        }).catch(err=>{
            console.log(err)
            return false
        })
        ElMessage.error('Login Failed')
        return response
    }
    const logout = ()=>{
        token.value = ''
        isLogin.value = false
        userDetail.value = ()=>{return {}}
    }
    const getUserDetail = async ()=>{
        const response = await getUserDetailApi()
        userDetail.value = response.data
    }
    return{
        token,
        isLogin,
        userDetail,
        login,
        logout
    }
},{
    persist:{
        storage:localStorage,
        key:"StateStore",
        enabled:true,
    }
})